<template>
  <div class="login-container">
    <h2>登录界面</h2>
    <el-form ref="loginForm" :model="formData" label-width="80px">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input v-model="formData.pass" placeholder="请输入密码" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitLogin">登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { userLoginService } from '@/api/user'
import { useUserStore } from '@/stores' // 根据实际存储模块路径引入

// 表单数据
const formData = ref({
  name: 'admin',
  pass: '1'
})
//用于前端校验表单数据
const loginForm = ref()

// 获取Pinia存储模块实例
const userStore = useUserStore()

// 登录处理函数
const submitLogin = async () => {
  // 先进行表单验证
  await loginForm.value.validate()

  const res = await userLoginService(formData.value)

  console.log('准备存储token，值为：', res.data.token)
  // 登录成功，将token存入Pinia
  userStore.setToken(res.data.token)
  console.log('已存储token，当前token值：', userStore.token)
  ElMessage.success('登录成功')
}

const resetForm = () => {
  formData.name = ''
  formData.pass = ''
  loginForm.value.clearValidate()
}
</script>

<style scoped>
.login-container {
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}
</style>
